<?php

namespace App\Repository\Db;

use App\Repository\Contracts\MessageInterface;
use App\Repository\Contracts\MessageTemplateInterface;

/**
 * @Author:: HuangYin
 * @DateTime: 2017/6/14 22:46
 */
class MessageRepository extends Repository implements MessageInterface
{
    protected $rules = [
        'created' => [
            'phone' => 'required|regex:/^1[34578][0-9]{9}$/'
        ]
    ];

    protected $messages = [
        'phone.required' => '手机号码不能为空',
        'phone.regex' => '手机号码不合法'
    ];

    protected function modelName()
    {
        return 'App\Model\Message';
    }

    public function created(array $data, $tid = 1)
    {
        $this->validate($data, 'created');
        if ($template = $this->container->make(MessageTemplateInterface::class)->detail($tid)) {
            // TODO 第三方发送短信
            // $sendContent = str_replace('$code', $data['code'], $template->content);

            return $this->save($data);
        }

        return false;
    }

    public function lists($limit, $page, $map = [])
    {
        $query = $this->searchMap($map);
        $total = $query->count();
        $list = $query->orderBy('id', 'desc')->simplePaginate($limit, ['*'], 'page', $page);

        return $this->simplePaginate('list', $list->items(), $total);
    }
}